using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Sockets;
using ServerPattern;
using HTA.Bluetooth;
using System.Xml.Serialization;

namespace CommandServer
{
	public class CommandHandler : AbstractBTHandler
	{
		private StreamReader sr;
		private StreamWriter sw;
        private NetworkStream nws;
       // private Robot robot;

		public CommandHandler(BluetoothClient client) : base (client) {
			Console.WriteLine("Incoming connection " + client.GetSocket().RemoteEndPoint);
			nws = client.GetStream();
			sr = new StreamReader(nws);
			sw = new StreamWriter(nws);
		}

		override protected Boolean ReadRequest() {
            WriteOut("incoming");
            BTXMLDriveCom RobotData = (BTXMLDriveCom)DeserializeXML(nws);
            WriteOut("XML Object deserialized");

            if (RobotData.Command == Command.GO)
            {
                
            }
            
            /*
			using (StreamWriter sw = new StreamWriter("protokoll.txt"))
			{
				sw.WriteLine("test");
			}
            */
			return true;
		}

		override protected void CreateResponse() {
			sw.WriteLine("Hello world.");
			sw.Flush();
		}

        private Object DeserializeXML(NetworkStream n)
        {
            //Write all data into MemoryStream
            MemoryStream ms = new MemoryStream();
            //Read first Byte in order to access the cl.DataAvailable property
            ms.WriteByte((byte)n.ReadByte());
            
            while (n.DataAvailable)
            {
                ms.WriteByte((byte)n.ReadByte());
            }

            ms.Position = 0;
            XmlSerializer xml = new XmlSerializer(typeof(BTXMLDriveCom));
            Object obj = xml.Deserialize(ms);

            return obj;
        }

        private void WriteOut(string s)
        {
            Console.WriteLine(s);
        }
	}
}
